package com.jgzx.config;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.jgzx.utils.AppContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * @author jackesy
 * @className: MybatisPlusConfig
 * @description: mybatis-plus配置
 * @create 2021/2/22 16:17
 **/
@Slf4j
@Configuration
@MapperScan("com.jgzx.mapper")
public class MybatisPlusConfig implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Date now = DateUtil.date();
        Long user_id = AppContextUtil.getUserId();
        this.setFieldValByName("create_time", now, metaObject);
        this.setFieldValByName("update_time", now, metaObject);
        if(user_id !=null) {
            this.setFieldValByName("create_user_id", user_id, metaObject);
            this.setFieldValByName("update_user_id", user_id, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date now = DateUtil.date();
        Long user_id = AppContextUtil.getUserId();
        this.setFieldValByName("update_time", now, metaObject);
        if(user_id !=null) {
            this.setFieldValByName("update_user_id", user_id, metaObject);
        }
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

}
